const fs = require("fs-extra");
const path = require("path");
const resolve = require("resolve");

function resolvePlugin(config) {
  return {
    name: "vite:resolve",
    resolveId(importee, importer) {
      // 如果这个相对于项目根目录的绝对路径： /src/main.js
      if (importee.startsWith("/")) {
        return {
          id: "/" + importee.slice(1),
          // id: path.resolve(importee.slice(1)),
        };
      }

      // 如果是磁盘的绝对路径： C:\xxx\index.html
      if (path.isAbsolute(importee)) {
        return {
          id: importee,
        };
      }

      // 如果是相对路径
      if (importee.startsWith(".")) {
        const baseDir = path.dirname(importer);
        const fsPath = path.resolve(baseDir, importee);
        return { id: fsPath };
      }

      // 其他就是引入的第三方模块
      const res = tryNodeResolve(importee, importer, config);
      if (res) {
        return res;
      }
    },
  };
}
function tryNodeResolve(importee, importer, config) {
  const pkgPath = resolve.sync(`${importee}/package.json`, {
    basedir: config.root,
  });
  const pkgDir = path.dirname(pkgPath);
  const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
  const entryPoint = pkg.module; // 包文件的描述 module 属性，指向此模块的 ES6 代码
  const entryPointPath = path.join(pkgDir, entryPoint);

  return {
    id: entryPointPath,
  };
}

module.exports = resolvePlugin;
